/**
 * 封装了一些网络请求方法，方便通过 Promise 的形式请求接口
 */

const TIMEOUT = 8000

Promise.prototype.finally = function (callback) {
    const P = this.constructor
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason =>
            P.resolve(callback()).then(() => {
                throw reason
            })
    )
}


/**
   * 拼接get参数
   */
function queryString(url, query) {
    let str = []
    for (let key in query) {
        str.push(key + '=' + query[key])
    }
    let paramStr = str.join('&')
    return paramStr ? `${url}?${paramStr}` : url
}


/**
 * 处理网络请求，timeout 是网络请求超时之后返回，默认 8s 可自行修改
 * @param params
 */
function requestHandle(params, page_name) {

    try {
        return Promise.race([
            fetchPromise(params, page_name),
        ])
    } catch (error) {
        console.log(error)
    }
}

export default {
    post: function (url, params, page_name) {
        return requestHandle({
            method: 'post',
            url: url,
            data: params
        }, page_name)
    },
    get: function (url, params, page_name) {
        return requestHandle({
            method: 'get',
            url: queryString(url, params)
        }, page_name)
    },
    put: function (url, params, page_name) {
        return requestHandle({
            method: 'put',
            url: url,
            data: params
        }, page_name)
    },
    delete: function (url, params, page_name) {
        return requestHandle({
            method: 'delete',
            url: url,
            data: params
        }, page_name)
    }
    // 如果，method 您需要更多类型，可自行添加更多方法；
}
